//
//  ChoosePatientViewController.m
//  HarmonizePub
//
//  Created by Haven on 16/9/26.
//  Copyright © 2016年 Zy. All rights reserved.
//


/**
 * You may think you know what the following code does.
 * But you dont. Trust me.
 * Fiddle with it, and youll spend many a sleepless.
 * night cursing the moment you thought youd be clever.
 * enough to "optimize" the code below.
 * Now close this file and go play with something else.
 *
 * 你可能会认为你读得懂以下的代码。但是你不会懂的，相信我吧.
 * 要是你尝试玩弄以下的代码的话，你将会在无尽的通宵中不断地咒骂自己为什么会认为自己聪明到可以优化这段代码.
 * 现在请关闭这个文件去玩点别的吧.
 */


#import "ChoosePatientViewController.h"
#import "Config.h"
#import "User.h"
#import "Patient.h"
#import <MJExtension.h>
#import "PatientManagerTableViewCell.h"
#import "AddPatientController.h"
#import "ReportController.h"
#import "LoginController.h"
#import "WebViewController.h"

@interface ChoosePatientViewController () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *patientTableView;
@property (nonatomic, strong) NSArray *patients;
@property (nonatomic, strong) NSString *nextController;
@property (nonatomic, assign) XHPatientListType type;

@end

@implementation ChoosePatientViewController

static NSString * const CellIdentifier = @"Cell";

/**
 * no comments for you.
 * it was hard to write.
 * so it should be hard to read.
 *
 * 难写的代码，肯定很难读。因此，我没有注释留给你.
 */
+ (void)patientWithCurrentController:(UIViewController *)controller nextController:(NSString *)nextController patientListType:(XHPatientListType)type {
//    XHLog(@"%@", XHUserPath)
    NSDictionary *rootDict = [NSDictionary dictionaryWithContentsOfFile:XHPatientListPath];
    NSArray *patientArray = [self arrayWithDataDictionary: rootDict patientListType:type];
    User *user = [NSKeyedUnarchiver unarchiveObjectWithFile:XHUserPath]; 
    if (user == nil) {
        // 登录
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:@"您还未登录，请先登录再操作!" preferredStyle:UIAlertControllerStyleAlert];
        __weak typeof(controller) weakController = controller;
        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LoginController *login = [[LoginController alloc] init];
            [weakController presentViewController:login animated:YES completion:nil];
        }];
        [alertController addAction:defaultAction];
        [controller presentViewController:alertController animated:YES completion:nil];
    } else if (patientArray.count) {
        if (patientArray.count == 1) {
            [Patient mj_objectWithKeyValues:patientArray.lastObject];
            UIViewController *viewController = [[NSClassFromString(nextController) alloc] init];
            if ([nextController isEqualToString: @"ReportController"]) {
                ReportController *reportVc = (ReportController *)viewController;
                reportVc.titleType = type;
                [controller.navigationController pushViewController:reportVc animated:YES];
            }else{
                [controller.navigationController pushViewController:viewController animated:YES];
            }
        } else {
            // 选择就诊人
            ChoosePatientViewController *choosePatient = [[self alloc] init];
            choosePatient.patients = patientArray;
            choosePatient.nextController = nextController;
            choosePatient.type = type;
            [controller.navigationController pushViewController:choosePatient animated:YES];
        }
    } else {
        // 添加就诊人
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提 示:" message:@"您还未绑定就诊人，请先绑定就诊人再操作！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        __weak typeof(controller) weakController = controller;
        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            AddPatientController *addPatient =[AddPatientController addPatientWithAddSuccess:^{
                UIViewController *viewController = [[NSClassFromString(nextController) alloc] init];
                [weakController.navigationController pushViewController:viewController animated:YES];
            }];
            addPatient.type = type;
            [weakController.navigationController pushViewController:addPatient animated:YES];
        }];
        [alert addAction:cancelAction];
        [alert addAction:defaultAction];
        [controller presentViewController:alert animated:YES completion:nil];
    }
}

+ (NSArray *)arrayWithDataDictionary:(NSDictionary *)dataDict patientListType:(XHPatientListType)type {
    NSMutableArray *arrayM = [NSMutableArray array];
    NSArray *medicalArray = dataDict[XHMedicalListKey]; // 门诊
    NSArray *inpatientArray = dataDict[XHInpatientLisyKey]; // 住院
    if (type == XHPatientListTypeMedical) {
        // 门诊
        arrayM = [medicalArray mutableCopy];
    } else if (type == XHPatientListTypeInpatient) {
        // 住院
        arrayM = [inpatientArray mutableCopy];
    } else {
        for (NSDictionary *dataDict in medicalArray)
            [arrayM addObject:dataDict];
        for (NSDictionary *dataDict in inpatientArray)
            [arrayM addObject:dataDict];
    }
    return arrayM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择就诊人";
    _patientTableView.layer.cornerRadius = 5.0f;
    _patientTableView.layer.masksToBounds = YES;
    _patientTableView.layer.borderWidth = 0.5f;
    _patientTableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    UINib *nib = [UINib nibWithNibName:[PatientManagerTableViewCell registerName] bundle:nil];
    [_patientTableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSDictionary *rootDict = [NSDictionary dictionaryWithContentsOfFile:XHPatientListPath];
    NSArray *array = [ChoosePatientViewController arrayWithDataDictionary:rootDict patientListType:self.type];
    self.patients = array;
    [self.patientTableView reloadData];
}

#pragma mark - 添加就诊人
- (IBAction)addPatientEvent:(UIButton *)sender {
    AddPatientController *addPatient = [[AddPatientController alloc] init];
    addPatient.type = self.type;
    [self.navigationController pushViewController:addPatient animated:YES];
}

#pragma mark - tableView delegate/dataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.patients.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [PatientManagerTableViewCell cellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PatientManagerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.isHiden = YES;
    [cell setCellShowDataWithDataDictionary:self.patients[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dataDict = self.patients[indexPath.row];
    [Patient mj_objectWithKeyValues:dataDict];
    
    UIViewController *viewController = [[NSClassFromString(self.nextController) alloc] init];
    if ([self.nextController isEqualToString: @"ReportController"]) {
        ReportController *reportVc = (ReportController *)viewController;
        reportVc.titleType = self.type;
        [self.navigationController pushViewController:reportVc animated:YES];
    }else if ([self.nextController isEqualToString: @"/ws/user/getZySsap"]){
        WebViewController *webView = [[WebViewController alloc] init];
        webView.title = @"手术安排";
        webView.url = [URLTool webURLStringWithPathString_shoushu:self.nextController token:[UserDefaultsTool stringForKey:XHToken] ID:[Patient sharedPatient].id];
        [self.navigationController pushViewController:webView animated:YES];
    }else{
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

@end
